<!--
 * @Author: 小花
 * @Date: 2022-01-22 14:12:41
 * @LastEditors: 小花
 * @LastEditTime: 2022-05-19 17:16:44
 * @Description: 新用户类型选择页面
-->
<template>
  <div class="newUser_container">
    <div class="title">请选择你的身份</div>
    <div class="body">
      <el-card class="box-card" shadow="hover" @click.native="selectUserType(item.type)"
        v-loading="fullscreenLoading" v-for="(item, index) in sysUserType" :key="index">
        <div class="box-card-body">
          <!-- 头像 -->
          <elImage :src="item.src"></elImage>
          <!-- 用户类型 -->
          <span :data-usertype="item.type">{{ item.name }}</span>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import elImage from '@/public/el-image/el-image.vue';
import { saveLoginInfo } from '@/js/public';
import user from '@/assets/images/user.webp'
import worker from '@/assets/images/worker.webp'

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    elImage
  },
  data () {
    //这里存放数据
    return {
      sysUserType: [
        {
          type: 'user',
          name: '用户',
          src: user
        },
        {
          type: 'worker',
          name: '维修员',
          src: worker
        }
      ],
      fullscreenLoading: false
    };
  },
  /**
   * @description: 获取路由params参数
   * @param {*} to
   * @param {*} from
   * @param {*} next
   * @return {*}
   * @author: 小花
   */
  beforeRouteEnter (to, from, next) {
    let code = to.params.code;
    if (!code) {
      next(vm => {
        vm.$router.go(-1);
        alert('请使用微信扫描二维码登录');
      });
    } else {
      next();
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    /**
     * @description: 获取可注册的用户类型。页面加载执行
     * @param {*}
     * @return {*}
     */
    async getUserRole () {
      /**
       * perm_name: "worker"
        role_id: "1524642919015792641"
        role_name: "维修员"
       */
      const result = await (await this.axios.get("/wx/getUserRole")).data
      this.sysUserType = []
      console.log(result)
      result.data.forEach(item => {
        const obj = {
          id: item.role_id,
          type: item.perm_name,
          name: item.role_name,
          src: item.perm_name === 'worker' ? worker : user
        }
        this.sysUserType.push(obj)
      })
    },

    /**
     * @description: 获取用户选择注册的用户类型
     * @param {*} userType
     * @return {*}
     */
    selectUserType (userType) {
      // {code: '43007', userType: 'user', state: '1652505341279', invitationCode: '', id: '1524642948199759874'}
      let json = {
        // 新用户注册码
        code: this.$route.params.code,
        // 注册用户类型
        userType,
        // 用户角色ID
        id: this.sysUserType.find(item => item.type === userType).id,
        // 会话ID
        state: sessionStorage.getItem('socketID'),
        // 邀请码
        invitationCode: ''
      }

      this.fullscreenLoading = true;
      if (userType === 'user') {
        this.regisiter(json)
      }

      if (userType == 'worker') {
        this.workerRegCodeCheck().then(res => {
          json.invitationCode = res;
          this.regisiter(json);
        }).catch(err => {
          this.fullscreenLoading = false;
        })
      }
    },

    /**
     * @description: worker注册邀请码验证
     * @param {*}
     * @return {*}
     */
    workerRegCodeCheck () {
      return new Promise((resolve, reject) => {
        this.$prompt('请输入邀请码', '提示', {
          inputValue: "",
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\d{6}$/,
          inputErrorMessage: '邀请码格式错误'
        }).then(({ value }) => {
          this.axios.post("/workerHome/codeCheck", { value }).then(res => {
            if (res.data.code == 43000) {
              this.$message.success(res.data.msg);
              resolve(value);
            } else if (res.data.code == 43001) {
              this.$message.error(res.data.msg);
              reject(true)
            }
          })
        })
      })
    },

    /**
     * @description: 注册触发器 -- 核心
     * @param {*} json 注册信息
     * @return {*}
     */
    regisiter (json) {
      this.axios.post('/wx/newUserRegister', json).then(res => {
        // 注册成功 43011
        if (res.data.code === 43011) {
          saveLoginInfo(res.data.data);
          this.$router.replace({ name: res.data.data.loginType });
        }
        this.fullscreenLoading = false;
      });
    },


  },
  created () {
    /**
     * @description: 页面加载执行，获取注册用户类型列表
     * @param {*}
     * @return {*}
     */
    this.getUserRole()
  }
};
</script>

<style lang="scss" scoped>
//@import url(); 引入公共css类
.newUser_container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0 10px;
  .title {
    font-size: 2rem;
    padding: 2rem;
  }
  .body {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    .box-card {
      width: 20rem;
      height: 20rem;
      margin: 5px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: grey;
      &:hover {
        border: 1px solid chocolate;
        color: chocolate !important;
        cursor: pointer;
      }
      .box-card-body {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        .el-image_container {
          width: auto;
        }
        span {
          margin-top: 2rem;
          font-size: 1.4rem;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
